package org.computate.controller.filter;

import java.io.IOException;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.computate.model.dao.Daos;
import org.computate.model.dao.PageDao;
import org.computate.model.item.Page;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class Filter_page implements Filter {
	
	@Inject private PageDao pageDao;
	@Inject private Daos daos;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		Page page = pageDao.ofy().query(Page.class).filter("name", "Home Page").get();
		List<Page> pages = pageDao.ofy().query(Page.class).list();
		
		if(page == null) {
			page = new Page();
			page.setName("Home Page");
			page.setDescription("This is the <b>page</b>");
			pageDao.put(page);
		}
		else {
			page.addItems(2, daos);
		}
		
		httpRequest.setAttribute("page", page);
		httpRequest.setAttribute("pages", pages);
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

}
